//
//  PHPhotoLibrary+Extension.m
//  06-录制视频
//
//  Created by monkey on 2017/7/31.
//  Copyright © 2017年 itcast. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PHPhotoLibrary+Extension.h"

@implementation PHPhotoLibrary (Extension)

#pragma mark - 保存至相册
+(void)saveImage:(UIImage *)image assetCollectionName:(NSString *)collectionName completionHandle:(void (^)(BOOL, NSError * _Nullable))completionHandle
{
    [self saveImage:image imageFileURL:nil VideoAtFileURL:nil assetCollectionName:collectionName completionHandle:completionHandle];
}

+ (void)saveVideo:(NSURL *)videoFileURL assetCollectionName:(NSString *)collectionName completionHandle:(void (^)(BOOL, NSError * _Nullable))completionHandle
{
    [self saveImage:nil imageFileURL:nil VideoAtFileURL:videoFileURL assetCollectionName:collectionName completionHandle:completionHandle];
}

+ (void)saveImageWithFileURL:(NSURL *)imageFileURL assetCollectionName:(NSString *)collectionName completionHandle:(void (^)(BOOL, NSError * _Nullable))completionHandle
{
    [self saveImage:nil imageFileURL:imageFileURL VideoAtFileURL:nil assetCollectionName:collectionName completionHandle:completionHandle];
}

#pragma mark - 内部方法

+ (void)saveImage:(UIImage *)image imageFileURL:(NSURL *)imageFileURL VideoAtFileURL:(NSURL *)videoFileURL assetCollectionName:(NSString *)collectionName completionHandle:(void (^)(BOOL success, NSError *error))completionHandle
{
    // 1. 获取当前App的相册授权状态
    PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
    
    // 2. 判断授权状态
    if (authorizationStatus == PHAuthorizationStatusAuthorized) {
        // 2.1 如果已经授权, 保存图片(调用步骤2的方法)
        [self saveImage:image imageFileURL:imageFileURL VideoAtFileURL:videoFileURL toCollectionWithName:collectionName completionHandle:completionHandle];
        
    } else if (authorizationStatus == PHAuthorizationStatusNotDetermined) { // 如果没决定, 弹出指示框, 让用户选择
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            // 如果用户选择授权, 则保存图片
            if (status == PHAuthorizationStatusAuthorized) {
                [self saveImage:image imageFileURL:imageFileURL VideoAtFileURL:videoFileURL toCollectionWithName:collectionName completionHandle:completionHandle];
            }
        }];
    } else {
        NSError *error = [NSError errorWithDomain:@"error" code:100000001 userInfo:@{@"reason": @"请在设置界面, 授权应用访问相册"}];
        completionHandle(NO,error);
    }
}

// 保存图片
+ (void)saveImage:(UIImage *)image imageFileURL:(NSURL *)imageFileURL VideoAtFileURL:(NSURL *)videoFileURL toCollectionWithName:(NSString *)collectionName completionHandle:(void (^)(BOOL success, NSError *error))completionHandle
{
    // 1. 获取相片库对象
    PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
    // 2. 调用changeBlock
    [library performChanges:^{
        
        // 2.1 创建一个相册变动请求
        PHAssetCollectionChangeRequest *collectionRequest;
        
        // 2.2 取出指定名称的相册
        PHAssetCollection *assetCollection = [self getCurrentPhotoCollectionWithTitle:collectionName];
        
        // 2.3 判断相册是否存在
        if (assetCollection) {
            // 如果存在就使用当前的相册创建相册请求
            collectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 如果不存在, 就创建一个新的相册请求
            collectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:collectionName];
        }
        
        // 2.4 根据传入的相片/视频, 创建变动请求
        PHAssetChangeRequest *assetRequest = nil;
        if (image != nil) {
            assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        } else if (videoFileURL != nil) {
            assetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoFileURL];
        } else if (imageFileURL != nil) {
            assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:imageFileURL];
        }
        
        // 2.4 创建一个占位对象
        PHObjectPlaceholder *placeholder = [assetRequest placeholderForCreatedAsset];
        // 2.5 将占位对象添加到相册请求中
        [collectionRequest addAssets:@[placeholder]];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        // 3. 判断是否出错, 如果报错, 声明保存不成功
        if (error) {
            completionHandle(NO,error);
        } else {
            completionHandle(YES,nil);
        }
    }];
}

/**
 根据相册名称获取对应的相册
 
 @param collectionName 相册名称
 @return PHAssetCollection
 */
+ (PHAssetCollection *)getCurrentPhotoCollectionWithTitle:(NSString *)collectionName {
    
    // 1. 创建搜索集合
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 2. 遍历搜索集合并取出对应的相册
    for (PHAssetCollection *assetCollection in result) {
        
        if ([assetCollection.localizedTitle containsString:collectionName]) {
            return assetCollection;
        }
    }
    
    return nil;
}

@end
